package com.esd.ps;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import com.esd.db.model.salary;
import com.esd.db.model.worker;
import com.esd.db.service.SalaryService;
import com.esd.db.service.VtdParameterService;
import com.esd.db.service.WorkerService;

@Controller
@Component
public class TaskM {
	@Autowired
	private SalaryService salaryService;
	@Autowired
	private WorkerService workerService;
	@Autowired
	private VtdParameterService paramService;
	/**
	 * 20160831--cx
	 * SpringMvc 定时 11:00--11:05 ,16:00--16:0 从0秒开始，每15秒一次 
	 */  
	@Scheduled(cron="0/15 0-5 11,16 * * ?")
	public void timer(){
		rebotSalary();
	}

	/**
	 * 20160831--cx
	 * 重置定时
	 */
	@Scheduled(cron="0 0 18 * * ? ")
	public void timerEnd(){
		resetVersion();
	}
	/**
	 * 20160831--cx
	 * 调用的任务
	 */
    public  void rebotSalary(){  
    	String workGroupSalaryString = paramService.selectRemarksByParamVlaueAndParamType("000004",Constants.WORK_GROUP);
    	double workGroupSalary = Double.parseDouble(workGroupSalaryString.split("/")[0]); //默认取的是一层工资计算
    	
		List<worker> list = null;
		list = workerService.getUIdAndWIdByVersionAndWGC(10000, "000004");
		if(!list.isEmpty()){
			//取随机数
			int z = (int) (Math.random() * ((list.size() - 1) + 1));
			
			int userId = list.get(z).getUserId();
			int workerId = list.get(z).getWorkerId();
			//随机数20-35
			int m = (int) (Math.random() * (15+1)) + 20;
			double d = (double)m*60;   
			//BigDecimal b = new BigDecimal(d);   
			//double tmt = b.setScale(12, BigDecimal.ROUND_HALF_UP).doubleValue();
			double x = (double) (Math.random() * (999+1))/1000;
			d = d + x;
			
			double salaryValue = d/3600*workGroupSalary;  //计算金钱
			salary s = new salary();
			
			s.setUserId(userId);
			s.setWorkerId(workerId);
			s.setMarkTimeTotle(d);
			s.setTimer(new Date());
			s.setSalaryValue(salaryValue);  
			s.setTaskType(1);          //默认类型为1层
			
			salaryService.insertSelective(s);
			
			salary ss = new salary();
			
			ss.setUserId(userId);
			ss.setWorkerId(workerId);
			ss.setMarkTimeTotle(-d);
			ss.setTimer(new Date());
			ss.setPayOffTime(new Date());
			ss.setSalaryValue(-salaryValue);
			ss.setTaskType(1);
			
			salaryService.insertSelective(ss);
			
			worker w = new worker();
			
			w.setWorkerId(workerId);
			w.setVersion(11111);
			
			workerService.updateByPrimaryKeySelective(w);
		}
    }
    /**
     * 20160831--cx
     * 复位version
     */
    public void resetVersion(){
    	worker w = new worker();
    	w.setWorkGroupCode("000004");
    	w.setVersion(10000);
    	workerService.updateByWgc(w);
    }
}
